package com.cqhz.quwan.ui.buy

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.media.SoundPool
import android.os.Build
import android.os.Vibrator
import android.support.annotation.RequiresApi
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import android.widget.TextView
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.service.API
import com.cqhz.quwan.ui.base.GoBackActivity
import com.cqhz.quwan.ui.base.WebViewActivity
import com.cqhz.quwan.ui.buy.adapter.BlueBallAdapter
import com.cqhz.quwan.ui.buy.adapter.RedBallAdapter
import com.cqhz.quwan.ui.widget.AutoHeightGridView
import com.cqhz.quwan.util.combine
import com.cqhz.quwan.util.random
import com.cqhz.quwan.util.v
import me.militch.quickcore.core.HasDaggerInject

class BallSelectorActivity : GoBackActivity(), SensorEventListener, HasDaggerInject<ActivityInject> {
    private val SENSOR_VALUE = 18

    override fun onAccuracyChanged(p0: Sensor?, p1: Int) {
    }

    override fun onSensorChanged(p0: SensorEvent?) {
        val sensorType = p0?.sensor?.type
        val values = p0?.values
        if(sensorType == Sensor.TYPE_ACCELEROMETER){
            if((Math.abs(values!![0]) > SENSOR_VALUE
                            || Math.abs(values[1]) > SENSOR_VALUE
                            || Math.abs(values[2]) > SENSOR_VALUE)){
                val t = System.currentTimeMillis() - mOldShakeTime
                if(t >= 1500){
                    mVibrator.vibrate(100)
                    mSoundPool.play(mSoundId,1f,1f,1,0,1f)
                    machineSelect()
                    mOldShakeTime = System.currentTimeMillis()
                }
            }
        }
    }
    override fun inject(t: ActivityInject?) {
        t?.inject(this)
    }
    private lateinit var mSensorManager:SensorManager
    private lateinit var mVibrator:Vibrator
    private lateinit var mSoundPool:SoundPool
    private val redBallGv by v<AutoHeightGridView>(R.id.red_ball_selector)
    private val blueBallGv by v<AutoHeightGridView>(R.id.blue_ball_selector)
    private val btnClear by v<TextView>(R.id.tv_ball_clear)
    private val frontCountLabel by v<TextView>(R.id.tv_front_count)
    private val backCountLabel by v<TextView>(R.id.tv_back_count)
    private val machineSelectBtn by v<TextView>(R.id.tv_machine_select)
    private val resultLabel by v<TextView>(R.id.label_result)
    private val shakeBtn by v<TextView>(R.id.tv_shake)
    private val confirmBtn by v<TextView>(R.id.btn_confirm)
    private val frontUsableCountTv by v<TextView>(R.id.tv_front_usable_count)
    private val backUsableCountTv by v<TextView>(R.id.tv_back_usable_count)
    private lateinit var redBallAdapter: RedBallAdapter
    private lateinit var blueBallAdapter: BlueBallAdapter
    private val redBalls = ArrayList<Int>()
    private val blueBalls = ArrayList<Int>()
    private var mSoundId:Int = -1
    private var mOldShakeTime:Long = -1
    private var lotteryId:String? = null
    private var periodNum:String? = null
    private var isReset:Boolean = false
    private var resetIndex:Int = -1
    private var lotteryType:Int = KeyContract.LotteryType_SSQ
    private lateinit var dropdownMenu:PopupWindow
    private lateinit var dropdownMenu2:PopupWindow
    private val dropdownMenuSize = IntArray(2)
    private val dropdownMenuSize2 = IntArray(2)
    override fun layout(): Int {
        return R.layout.activity_ball_selector
    }

    override fun titleBarRightIconResId(): Int? {
        return R.drawable.icon_more
    }

    override fun onTitleBarRightClick(v:View) {
        val location = IntArray(2)
        v.getLocationOnScreen(location)
        dropdownMenu2.showAsDropDown(v)
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun initView() {
        lotteryType = intent.getIntExtra(KeyContract.LotteryType,KeyContract.LotteryType_SSQ)
        dropdownMenu = createPopupWindow1()
        dropdownMenu2 = createPopupWindow2()
        if(lotteryType == KeyContract.LotteryType_SSQ){
            setTitleBarText("双色球")
            val frontText = "个（可选6-33个红球）"
            val backText = "个（可选1-16个蓝球）"
            frontUsableCountTv.text = frontText
            backUsableCountTv.text = backText
        }else if(lotteryType == KeyContract.LotteryType_DLT){
            setTitleBarText("大乐透")
            val frontText = "个（可选5-35个红球）"
            val backText = "个（可选2-12个蓝球）"
            frontUsableCountTv.text = frontText
            backUsableCountTv.text = backText
        }

        mSensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
        mVibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        mSoundPool = SoundPool.Builder().setMaxStreams(1).build()
        mSoundId = mSoundPool.load(this,R.raw.shake_sound_male,1)
        val reds = intent.getIntArrayExtra(KeyContract.RedBalls)
        val blues = intent.getIntArrayExtra(KeyContract.BlueBalls)
        lotteryId = intent.getStringExtra(KeyContract.LotteryId)
        periodNum = intent.getStringExtra(KeyContract.PeriodNum)
        isReset = intent.getBooleanExtra(KeyContract.IsReset,false)
        resetIndex = intent.getIntExtra(KeyContract.ResetIndex,-1)
        if(reds!=null){
            redBalls.addAll(reds.toList())
        }
        if(blues!=null){
            blueBalls.addAll(blues.toList())
        }
        redBallAdapter = RedBallAdapter(this)
        blueBallAdapter = BlueBallAdapter(this)
        if(lotteryType == KeyContract.LotteryType_SSQ){
            redBallAdapter.setData((1 .. 33).toList())
            blueBallAdapter.setData((1 .. 16).toList())
        }else if(lotteryType == KeyContract.LotteryType_DLT){
            redBallAdapter.setData((1 .. 35).toList())
            blueBallAdapter.setData((1 .. 12).toList())
        }
        redBallGv.adapter = redBallAdapter
        blueBallGv.adapter = blueBallAdapter
        redBallAdapter.setChecks(redBalls)
        blueBallAdapter.setChecks(blueBalls)
        shakeBtn.setOnClickListener {
            machineSelect()
        }
        btnClear.setOnClickListener {
            clearAndReset()
        }
        redBallAdapter.setOnSelectListener {
            redBalls.clear()
            redBalls.addAll(it)
            resetCountLabel()
            resetCalc()
        }
        blueBallAdapter.setOnSelectListener {
            blueBalls.clear()
            blueBalls.addAll(it)
            resetCountLabel()
            resetCalc()
        }
        machineSelectBtn.setOnClickListener {
            val location = IntArray(2)
            it.getLocationOnScreen(location)
            dropdownMenu.showAtLocation(it,Gravity.NO_GRAVITY,location[0]-dropdownMenuSize[0],location[1]-dropdownMenuSize[1]-10)
        }
        confirmBtn.setOnClickListener {
            if(lotteryType == KeyContract.LotteryType_SSQ){
                if(redBalls.size >= 6 && blueBalls.size >= 1){
                    if((lotteryId != null && periodNum != null)||isReset||(lotteryId == null && periodNum == null )){
                        val intent = Intent()
                        intent.putExtra(KeyContract.RedBalls,redBalls.sorted().toIntArray())
                        intent.putExtra(KeyContract.BlueBalls,blueBalls.sorted().toIntArray())
                        intent.putExtra(KeyContract.PeriodNum,periodNum)
                        intent.putExtra(KeyContract.LotteryId,lotteryId)
                        intent.putExtra(KeyContract.IsReset,isReset)
                        intent.putExtra(KeyContract.ResetIndex,resetIndex)
                        intent.putExtra(KeyContract.LotteryType,KeyContract.LotteryType_SSQ)
                        intent.setClass(this, LotteryBettingActivity::class.java)
                        startActivity(intent)
                        finish()
                    }
                }else{
                    showToast("至少选择一注")
                }
            }else if(lotteryType == KeyContract.LotteryType_DLT){
                if(redBalls.size >= 5 && blueBalls.size >= 2){
                    if((lotteryId != null && periodNum != null)||isReset||(lotteryId == null && periodNum == null )){
                        val intent = Intent()
                        intent.putExtra(KeyContract.RedBalls,redBalls.sorted().toIntArray())
                        intent.putExtra(KeyContract.BlueBalls,blueBalls.sorted().toIntArray())
                        intent.putExtra(KeyContract.PeriodNum,periodNum)
                        intent.putExtra(KeyContract.LotteryId,lotteryId)
                        intent.putExtra(KeyContract.IsReset,isReset)
                        intent.putExtra(KeyContract.ResetIndex,resetIndex)
                        intent.putExtra(KeyContract.LotteryType,KeyContract.LotteryType_DLT)
                        intent.setClass(this, LotteryBettingActivity::class.java)
                        startActivity(intent)
                        finish()
                    }
                }else{
                    showToast("至少选择一注")
                }
            }
        }
        resetCountLabel()
        resetCalc()
    }


    private fun gen(num:Int){
        val intent = Intent()
        intent.putExtra(KeyContract.RedBalls,redBalls.toIntArray())
        intent.putExtra(KeyContract.BlueBalls,blueBalls.toIntArray())
        intent.putExtra(KeyContract.PeriodNum,periodNum)
        intent.putExtra(KeyContract.LotteryId,lotteryId)
        intent.putExtra(KeyContract.IsReset,isReset)
        intent.putExtra(KeyContract.ResetIndex,resetIndex)
        intent.putExtra(KeyContract.LotteryType,lotteryType)
        intent.putExtra(KeyContract.Gen,num)
        intent.setClass(this, LotteryBettingActivity::class.java)
        startActivity(intent)
        finish()
    }


    override fun onStart() {
        super.onStart()
        val mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
        mSensorManager.registerListener(this,mSensor,SensorManager.SENSOR_DELAY_UI)
    }

    override fun onPause() {
        super.onPause()
        mSensorManager.unregisterListener(this)
    }


    private fun clearAndReset(){
        redBallAdapter.clearChecks()
        blueBallAdapter.clearChecks()
        redBalls.clear()
        blueBalls.clear()
        resetCountLabel()
        resetCalc()
    }

    private fun resetCountLabel(){
        frontCountLabel.text  = "${redBalls.size}"
        backCountLabel.text  = "${blueBalls.size}"
    }

    private fun resetCalc(){
        val resultCount:Long = when (lotteryType) {
            KeyContract.LotteryType_SSQ -> redBalls.size.combine(6)*blueBalls.size.combine(1)
            KeyContract.LotteryType_DLT -> redBalls.size.combine(5)*blueBalls.size.combine(2)
            else -> 0
        }
        val text = "一共 $resultCount 注，${resultCount*2} 元"
        resultLabel.text = text
    }

    private fun machineSelect(){
        redBalls.clear()
        blueBalls.clear()
        if(lotteryType == KeyContract.LotteryType_SSQ){
            redBalls.addAll((1..33).random(6).toList().sorted())
            blueBalls.addAll((1..16).random(1).toList().sorted())
        }else if(lotteryType == KeyContract.LotteryType_DLT){
            redBalls.addAll((1..35).random(5).toList().sorted())
            blueBalls.addAll((1..12).random(2).toList().sorted())
        }
        redBallAdapter.setChecks(redBalls)
        blueBallAdapter.setChecks(blueBalls)
        resetCountLabel()
        resetCalc()
    }
    private fun createPopupWindow1():PopupWindow{
        val view = layoutInflater.inflate(R.layout.layout_drapdown, null,false)
        val one = view.findViewById<TextView>(R.id.dropdown_one)
        val five = view.findViewById<TextView>(R.id.dropdown_five)
        val ten = view.findViewById<TextView>(R.id.dropdown_ten)
        one.setOnClickListener {
            dropdownMenu.dismiss()
            gen(1)
        }
        five.setOnClickListener {
            dropdownMenu.dismiss()
            gen(5)
        }
        ten.setOnClickListener {
            dropdownMenu.dismiss()
            gen(10)
        }
        view.measure(View.MeasureSpec.UNSPECIFIED,View.MeasureSpec.UNSPECIFIED)
        dropdownMenuSize[0] =view.measuredWidth
        dropdownMenuSize[1] =view.measuredHeight
        val window = PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true)
        window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        window.isOutsideTouchable = true
        window.isTouchable = true
        return window
    }
    private fun createPopupWindow2():PopupWindow{
        val view = layoutInflater.inflate(R.layout.layout_drapdown_more, null,false)
        val lishi = view.findViewById<TextView>(R.id.dropdown_lishi)
        val wanfa = view.findViewById<TextView>(R.id.dropdown_wanfa)
        lishi.setOnClickListener {
            dropdownMenu2.dismiss()
            val intent = Intent(this,WebViewActivity::class.java)
            intent.putExtra(KeyContract.Title,"历史开奖")
            val lotteryId = when(lotteryType){
                KeyContract.LotteryType_SSQ -> "11"
                KeyContract.LotteryType_DLT -> "14"
                else -> "11"
            }
            val url = "${API.LishiKaiJiang}?id=$lotteryId"
            intent.putExtra(KeyContract.Url, url)
            startActivity(intent)
        }
        wanfa.setOnClickListener {
            dropdownMenu2.dismiss()
            val intent = Intent(this,WebViewActivity::class.java)
            intent.putExtra(KeyContract.Title,"玩法说明")
            val url = "${API.Wanfa}?query=$lotteryId"
            intent.putExtra(KeyContract.Url,url)
            startActivity(intent)
        }
        view.measure(View.MeasureSpec.UNSPECIFIED,View.MeasureSpec.UNSPECIFIED)
        dropdownMenuSize2[0] =view.measuredWidth
        dropdownMenuSize2[1] =view.measuredHeight
        val window = PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true)
        window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        window.isOutsideTouchable = true
        window.isTouchable = true
        return window
    }

}